<script setup lang="ts">
import type { TransferDataItem } from 'element-plus'
import type { SystemAccount } from '@/apis/system/accountApi'
import { ref } from 'vue'
import { accountApi } from '@/apis/system/accountApi'
import { appRoleApi } from '@/apis/system/appRoleApi'

const dialogVisible = ref(false)
const formData = ref<Partial<SystemAccount>>()
const roles = ref<TransferDataItem[]>([])

async function open(accountId: number) {
  const account = await accountApi.findDetail(accountId)
  formData.value = {
    id: accountId,
    roleCodes: account.roleCodes ?? [],
  }
  const data = await appRoleApi.queryPage({ appType: account.appType, size: 50, current: 1 })
  if (data && data.records) {
    roles.value = data.records!.map((item) => {
      return {
        label: item.name,
        key: item.code,
        disabled: item.state === 'DISABLE',
      }
    })
  }
  dialogVisible.value = true
}

async function submitForm() {
  if (formData.value) {
    await accountApi.modify(formData.value)
    ElMessage.success('账号授权成功')
    dialogVisible.value = false
  }
}

defineExpose({ open })
</script>

<template>
  <el-dialog
    v-if="formData"
    v-model="dialogVisible"
    title="账号授权"
    width="600"
    destroy-on-close
    draggable
  >
    <el-transfer
      v-model="formData.roleCodes"
      filterable
      :data="roles"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
